<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

// Require login
requireLogin();

$user_id = $_SESSION['user_id'];
$user = getUserById($pdo, $user_id);

$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = sanitizeInput($_POST['first_name']);
    $last_name = sanitizeInput($_POST['last_name']);
    $email = sanitizeInput($_POST['email']);
    $phone = sanitizeInput($_POST['phone']);
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validation
    if (empty($first_name) || empty($last_name) || empty($email)) {
        $error_message = 'Please fill in all required fields.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'Please enter a valid email address.';
    } else {
        // Check if email is already taken by another user
        $existing_user = getUserByEmail($pdo, $email);
        if ($existing_user && $existing_user['id'] != $user_id) {
            $error_message = 'This email is already taken by another account.';
        } else {
            // Update user information
            try {
                $update_data = [$first_name, $last_name, $email, $phone, $user_id];
                $sql = "UPDATE users SET first_name = ?, last_name = ?, email = ?, phone = ? WHERE id = ?";
                
                // If changing password
                if (!empty($new_password)) {
                    if (empty($current_password)) {
                        $error_message = 'Please enter your current password to change it.';
                    } elseif (!password_verify($current_password, $user['password'])) {
                        $error_message = 'Current password is incorrect.';
                    } elseif ($new_password !== $confirm_password) {
                        $error_message = 'New passwords do not match.';
                    } elseif (strlen($new_password) < 6) {
                        $error_message = 'New password must be at least 6 characters long.';
                    } else {
                        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                        $sql = "UPDATE users SET first_name = ?, last_name = ?, email = ?, phone = ?, password = ? WHERE id = ?";
                        $update_data = [$first_name, $last_name, $email, $phone, $hashed_password, $user_id];
                    }
                }
                
                if (empty($error_message)) {
                    $stmt = $pdo->prepare($sql);
                    $result = $stmt->execute($update_data);
                    
                    if ($result) {
                        // Update session variables
                        $_SESSION['first_name'] = $first_name;
                        $_SESSION['last_name'] = $last_name;
                        $_SESSION['email'] = $email;
                        
                        $success_message = 'Profile updated successfully!';
                        
                        // Refresh user data
                        $user = getUserById($pdo, $user_id);
                    } else {
                        $error_message = 'Error updating profile. Please try again.';
                    }
                }
            } catch (PDOException $e) {
                $error_message = 'Error updating profile. Please try again.';
            }
        }
    }
}

$page_title = "My Profile";
?>
<?php include '../includes/header.php'; ?>

<main style="padding: 2rem 0;">
    <div class="container">
        <h1 style="margin-bottom: 2rem; color: #2c3e50;">My Profile</h1>

        <div style="display: grid; grid-template-columns: 1fr 2fr; gap: 2rem;">
            <!-- Profile Navigation -->
            <div class="card">
                <div class="card-header">
                    <h2>Account</h2>
                </div>
                <div style="display: flex; flex-direction: column; gap: 0.5rem;">
                    <a href="/chuan/535g/user/profile.php" class="btn btn-primary" style="text-align: left; justify-content: flex-start;">
                        <i class="fas fa-user"></i> Profile Information
                    </a>
                    <a href="/chuan/535g/user/orders.php" class="btn btn-outline" style="text-align: left; justify-content: flex-start;">
                        <i class="fas fa-shopping-bag"></i> My Orders
                    </a>
                    <a href="/chuan/535g/opencart_panel.php" class="btn btn-outline" style="text-align: left; justify-content: flex-start; background: #28a745; color: white; border-color: #28a745;">
                        <i class="fas fa-store"></i> OpenCart
                    </a>
                    <a href="/chuan/535g/auth/logout.php" class="btn btn-outline" style="text-align: left; justify-content: flex-start; color: #e74c3c;">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>

            <!-- Profile Form -->
            <div class="card">
                <div class="card-header">
                    <h2>Profile Information</h2>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success"><?php echo $success_message; ?></div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-error"><?php echo $error_message; ?></div>
                <?php endif; ?>
                
                <form method="POST" action="">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="first_name">First Name *</label>
                            <input type="text" id="first_name" name="first_name" required value="<?php echo htmlspecialchars($user['first_name']); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="last_name">Last Name *</label>
                            <input type="text" id="last_name" name="last_name" required value="<?php echo htmlspecialchars($user['last_name']); ?>">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="email">Email Address *</label>
                        <input type="email" id="email" name="email" required value="<?php echo htmlspecialchars($user['email']); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label for="phone">Phone Number</label>
                        <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                    </div>
                    
                    <div style="border-top: 1px solid #ecf0f1; padding-top: 2rem; margin-top: 2rem;">
                        <h3 style="margin-bottom: 1rem; color: #2c3e50;">Change Password</h3>
                        <p style="color: #7f8c8d; margin-bottom: 1.5rem; font-size: 0.9rem;">Leave blank to keep current password</p>
                        
                        <div class="form-group">
                            <label for="current_password">Current Password</label>
                            <input type="password" id="current_password" name="current_password">
                        </div>
                        
                        <div class="form-group">
                            <label for="new_password">New Password</label>
                            <input type="password" id="new_password" name="new_password" minlength="6">
                        </div>
                        
                        <div class="form-group">
                            <label for="confirm_password">Confirm New Password</label>
                            <input type="password" id="confirm_password" name="confirm_password" minlength="6">
                        </div>
                    </div>
                    
                    <div class="form-group" style="margin-top: 2rem;">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Profile
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<script>
// Password confirmation validation
document.getElementById('confirm_password').addEventListener('input', function() {
    const newPassword = document.getElementById('new_password').value;
    const confirmPassword = this.value;
    
    if (newPassword !== confirmPassword) {
        this.setCustomValidity('Passwords do not match');
    } else {
        this.setCustomValidity('');
    }
});

document.getElementById('new_password').addEventListener('input', function() {
    const confirmPassword = document.getElementById('confirm_password');
    if (confirmPassword.value) {
        confirmPassword.dispatchEvent(new Event('input'));
    }
});
</script>

<?php include '../includes/footer.php'; ?>
